import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import querystring from 'querystring'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // withCredentials: true, // send cookies when cross-domain requests
  transformRequest: [function(data) {
    return querystring.stringify(data)
  }],
  timeout: 5000
})

service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    console.log(error)
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 0) {
      return res
    } else {
      if (res.code === 2000) {
        MessageBox.confirm(res.message, '提示', {
          type: 'warning',
          confirmButtonText: '确定',
          showClose: false,
          showCancelButton: false,
          closeOnPressEscape: false,
          closeOnClickModal: false
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      } else {
        Message({ message: res.message || 'Error', type: 'error', duration: 5 * 1000 })
      }
      return Promise.reject(new Error(res.message || 'Error'))
    }
  },
  error => {
    Message({ message: error, type: 'error', duration: 5 * 1000 })
    return Promise.reject(error)
  }
)

export default service
